package main

import (
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/kesilent/snippetsbox/models"
)

//初始页
func Index(c *gin.Context) {
	c.String(http.StatusOK, "welcome")
}

//获取全部标签
func GetAllTag(c *gin.Context) {
	tag, dberr := env.db.GetAllTag()
	if dberr != nil {
		panic(dberr)
	}
	c.JSON(http.StatusOK, tag)
	return
}

//添加标签
func AddTag(c *gin.Context) {
	tag := new(models.SnippTag)
	tag.UserId = 0
	tag.TagName = c.PostForm("name")
	status := c.PostForm("status")
	if status != "" {
		tag.TagStatus, _ = strconv.Atoi(status)
	} else {
		tag.TagStatus = 0
	}
	tag.TagTime, _ = time.Parse("2006-01--02 15:04:05", time.Now().Format("2006-01-02 15:04:05"))
	tagId := env.db.InsertTag(tag)

	c.String(http.StatusOK, strconv.FormatInt(tagId, 10))
	return
}

//通过标签ID获取代码列表
func GetCodeListForTagID(c *gin.Context) {
	postId := c.PostForm("tagid")
	tagId, _ := strconv.Atoi(postId)

	codeList, dbErr := env.db.GetCodeListForTag(tagId)
	if dbErr != nil {
		panic(dbErr)
	}
	c.JSON(http.StatusOK, codeList)
	return
}

//获取全部代码列表
func GetCodeListAll(c *gin.Context) {
	codeList, dbErr := env.db.GetCodeListAll()
	if dbErr != nil {
		panic(dbErr)
	}
	c.JSON(http.StatusOK, codeList)
	return
}

//增加代码
func AddCode(c *gin.Context) {
	code := new(models.SnippCode)

	code.UserId = 0
	typeId, _ := strconv.Atoi(c.PostForm("typeid"))
	code.TypeId = typeId
	code.CodeName = c.PostForm("codename")
	code.CodeContent = c.PostForm("codecontent")
	code.CodeAlias = c.PostForm("codealias")
	code.CodeStatus = 0
	code.CodeTime, _ = time.Parse("2006-01-02 15:04:05", time.Now().Format("2006-01-02 15:04:05"))

	var tagids = c.PostForm("tagids")

	codeId := env.db.InsertCode(code)

	env.db.InsertRelation(codeId, tagids)

	c.String(http.StatusOK, strconv.FormatInt(codeId, 10))

	return
}

//通过代码ID获取详细内容
func GetCodeForId(c *gin.Context) {
	postId := c.PostForm("codeid")
	codeId, _ := strconv.Atoi(postId)
	codeModel, dbErr := env.db.GetCodeForId(codeId)
	if dbErr != nil {
		panic(dbErr)
	}
	c.JSON(http.StatusOK, &codeModel)
	return
}
